package com.xoa.service.task.impl;



import cn.jpush.api.report.UsersResult;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.sms.SmsBodyMapper;
import com.xoa.dao.sms.SmsMapper;
import com.xoa.dao.smsSettings.SmsSettingsMapper;
import com.xoa.dao.task.TaskFeedbackMapper;
import com.xoa.dao.task.TaskManageMapper;
import com.xoa.dao.task.TaskUserMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysPara;
import com.xoa.model.department.Department;
import com.xoa.model.sms.Sms;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.sms.SmsBodyExtend;
import com.xoa.model.sms2.Sms2Priv;
import com.xoa.model.smsSettings.SmsSettings;
import com.xoa.model.task.TaskFeedback;
import com.xoa.model.task.TaskManage;
import com.xoa.model.task.TaskUser;
import com.xoa.model.users.Users;
import com.xoa.service.sms.SmsService;
import com.xoa.service.task.TaskManageService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import com.xoa.util.sendUtil.HttpSend;
import com.xoa.util.sendUtil.send;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class TaskManageServiceImpl implements TaskManageService {

    @Resource
    private TaskManageMapper taskManageMapper;

    @Resource
    private TaskUserMapper taskUserMapper;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private TaskFeedbackMapper taskFeedbackMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Autowired
    protected SmsService smsService;

    @Resource
    private SysParaMapper sysParaMapper;

    @Resource
    private SmsSettingsMapper smsSettingsMapper;

    @Resource
    private SmsBodyMapper smsBodyMapper;

    @Autowired
    protected SmsMapper smsMapper;

    @Override
    public ToJson addTaskManage(HttpServletRequest request, TaskManage taskManage) {
        ToJson toJson = new ToJson();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        try{
         /*    if(taskManage.getProgress()==100){
                 Date date = new Date();
                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                 String dateStr = sdf.format(date);
                 taskManage.setCompleteDate(dateStr);
                 taskManage.setTaskStatus(1);
             }*/
            taskManage.setCreateUser(users.getUserId());
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = sdf.format(date);
            taskManage.setCreateDate(dateStr);
            taskManageMapper.addTaskManage(taskManage);
            Map map = new HashMap();
            map.put("taskName",taskManage.getTaskName());
            map.put("manageUser",taskManage.getManageUser());
            map.put("createUser",taskManage.getCreateUser());
            map.put("importantLevel",taskManage.getImportantLevel());
            map.put("endDate",taskManage.getEndDate());
            //查询任务id
            int taskId = taskManageMapper.queryTaskId(map);
            TaskUser taskUser = new TaskUser();
            taskUser.setTaskId(taskId);
            if(!StringUtils.checkNull(taskManage.getShared())){
                //截取共享者
                String[] userNameArray= taskManage.getShared().split(",");
                for(String array:userNameArray){
                    taskUser.setUserId(array);
                    taskUser.setTaskRelation("3");
                    taskUserMapper.addTaskUser(taskUser);
                }
            }
            if(!StringUtils.checkNull(taskManage.getParticipate())){
                //截取参与者
                String[] userNameArray= taskManage.getParticipate().split(",");
                for(String array:userNameArray){
                    taskUser.setUserId(array);
                    taskUser.setTaskRelation("1");
                    taskUserMapper.addTaskUser(taskUser);
                }
            }
            toJson.setMsg("success");
            toJson.setFlag(0);
        }catch (Exception e){
            toJson.setMsg("erro");
            toJson.setFlag(1);
            e.printStackTrace();
        }

        return toJson;
    }

    @Override
    public ToJson<TaskManage> queryTaskManageByTaskId(HttpServletRequest request, int taskId) {
        ToJson<TaskManage> toJson = new ToJson<TaskManage>();
        List<TaskManage> taskManageList= new ArrayList<TaskManage>();
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse");
        try{
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            //查找事务提醒并消除
            Map mapTemp = new HashMap();
            mapTemp.put("type",31);
            mapTemp.put("id",taskId);
            mapTemp.put("userId",user.getUserId());
            List<Sms> smsList = smsMapper.querySmsByTypeAll(mapTemp);
            for (Sms sms : smsList) {
                //修正消除所有事务提醒的bug
                    sms.setRemindFlag("0");
                    smsMapper.updSmsById(sms);
            }
            TaskManage taskManage = new TaskManage();
            taskManage= taskManageMapper.queryTaskManageByTaskId(taskId);
            if(taskManage.getParentId()!=0){
                TaskManage taskManage1 = taskManageMapper.queryTaskManageByTaskId(taskManage.getParentId());
                taskManage.setParentName(taskManage1.getTaskName());
            }
            //找上级领导
            Users users = usersMapper.findUsersByuserId(taskManage.getManageUser());
            Department department = departmentMapper.selectByDeptId(users.getDeptId());
            if(department.getDeptParent()!=0){
                List list = getSuperiorDepartment(department.getDeptParent());
                Map mapd = new HashMap();
                mapd.put("userPriv",users.getUserPriv());
                mapd.put("deptIds",list);
                boolean istaskGrade = false;
                List<Users> usersList = usersMapper.querySubordinate1(mapd);
                for(Users users1 :usersList){
                    if(user.getUserId().equals(users1.getUserId())){
                        istaskGrade = true;
                    }
                }
            }

            if(taskManage!=null){
                if(!StringUtils.checkNull(taskManage.getManageUser())){
                    taskManage.setManageUserName(usersMapper.getUsernameByUserId(taskManage.getManageUser()));

                }
                if(!StringUtils.checkNull(taskManage.getCreateUser())){
                    taskManage.setCreateUserName(usersMapper.getUsernameByUserId(taskManage.getManageUser()));

                }
                switch (taskManage.getImportantLevel()){
                    case 1:
                        taskManage.setImportantLevelStr("重要");
                        break;
                    case 2:
                        taskManage.setImportantLevelStr("紧急");
                        break;
                    default:
                        taskManage.setImportantLevelStr("普通");
                        break;
                }
                Map map1 = new HashMap();
                map1.put("taskId",taskId);
                map1.put("taskRelation","1");
                //查出参与者与共享者
                List<String> userIdList = taskUserMapper.queryTaskUserId(map1);
                String participateStr = "";
                String participateName = "";
                String shared="";
                String sharedName = "";
                for(String s:userIdList){//参与者
                    participateName += s+",";
                    participateStr+= usersMapper.getUsernameByUserId(s)+",";
                }
                taskManage.setParticipateName(participateStr);
                taskManage.setParticipate(participateName);

                Map map2 = new HashMap();
                map2.put("taskId",taskId);
                map2.put("taskRelation","3");
                List<String> userIdL = taskUserMapper.queryTaskUserId(map2);
                for(String s:userIdL){//分享者
                    sharedName += s+",";
                    shared+= usersMapper.getUsernameByUserId(s)+",";
                }
                taskManage.setSharedName(shared);
                taskManage.setShared(sharedName);
                List<TaskManage>taskManages = new ArrayList<TaskManage>();
                taskManages = taskManageMapper.queryChildTaskManage(taskId);
                //如果有子任务
                taskManage.setTaskManages(taskManages);
                //查询反馈评论
                List<TaskFeedback> taskFeedbacks = taskFeedbackMapper.queryTaskFeedback(taskId);
                for(TaskFeedback t:taskFeedbacks){
                    t.setUserName(usersMapper.getUsernameByUserId(t.getUserId()));
                    //找到回复评论
                    t.setTaskFeedbacks(taskFeedbackMapper.queryReplyFeedback(t.getFeedbackId()));
                }
                taskManage.setTaskFeedbacks(taskFeedbacks);
                Map map = new HashMap();
                map.put("userId",user.getUserId());
                map.put("taskRelation","2");
                map.put("taskId",taskId);
                List<TaskUser> taskUsers = taskUserMapper.queryTaskUserIdByTaskId(map);
                if(taskUsers.size()>0){
                    taskManage.setFollow(1);
                }
                taskManage.setAttachmentList(GetAttachmentListUtil.returnAttachment(taskManage.getAttachmentName(), taskManage.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_TASKMANAGE));
                toJson.setFlag(0);
                toJson.setMsg("success");
                taskManageList.add(taskManage);
                toJson.setObj(taskManageList);
            }else{
                toJson.setFlag(1);
                toJson.setMsg("erro");
            }
        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg("erro");
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson updateTaskManage(HttpServletRequest request, TaskManage taskManage) {
        ToJson toJson = new ToJson();
        try{
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = sdf.format(date);
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            //判断是否关注
            switch (taskManage.getFollow()){
                case 1:
                    //关注
                    TaskUser taskUser = new TaskUser();
                    taskUser.setTaskId(taskManage.getTaskId());
                    taskUser.setUserId(users.getUserId());
                    taskUser.setTaskRelation("2");
                    taskUserMapper.addTaskUser(taskUser);
                    break;
                case 2:
                    //取消关注
                    Map map = new HashMap();
                    map.put("taskId",taskManage.getTaskId());
                    map.put("userId",users.getUserId());
                    map.put("taskRelation","2");
                    List<TaskUser> taskUsers = taskUserMapper.queryTaskUserIdByTaskId(map);
                    if(taskUsers.get(0).getTaskUserId()!=0){
                        taskUserMapper.deleteTaskUserByTaskUserId(taskUsers.get(0).getTaskUserId());
                    }
                    break;
                default:
                    //如果是0就是默认没有操作
                    break;
            }
            //点击已完成或者完成度为100
            if(taskManage.getProgress()==100||"1".equals(taskManage.getTaskStatus())){
                //查询当前任务是否有子任务
                List<TaskManage> taskManages = taskManageMapper.queryChildTaskManage(taskManage.getTaskId());
                if(taskManages.size()>0){
                    int count = taskManages.size();
                    int i =0;
                    for(TaskManage taskManag:taskManages){
                        if("1".equals(taskManag.getTaskStatus())){
                            i =i+1;
                        }
                    }
                    if(count==i){
                        taskManage.setCompleteDate(dateStr);
                        taskManage.setTaskStatus("1");
                        taskManage.setProgress(100);
                    }else{
                        toJson.setMsg("当前有子任务未完成");
                        toJson.setFlag(1);
                        return toJson;
                    }
                }else{
                    taskManage.setCompleteDate(dateStr);
                    taskManage.setTaskStatus("1");
                    taskManage.setProgress(100);
                }

            }
            if(!StringUtils.checkNull(taskManage.getTaskName())){
                Map map = new HashMap();
                map.put("taskId",taskManage.getTaskId());
                map.put("taskRelation","1");
                TaskUser taskUser = new TaskUser();
                taskUser.setTaskId(taskManage.getTaskId());
                //修改参与人
                if(!StringUtils.checkNull(taskManage.getParticipate())){
                    taskUserMapper.deleteTaskUserByTaskId(map);
                    String[] participateArray = taskManage.getParticipate().split(",");
                    for(String s:participateArray){
                        taskUser.setUserId(s);
                        taskUser.setTaskRelation("1");
                        taskUserMapper.addTaskUser(taskUser);
                    }
                }else{
                    //清空
                    taskUserMapper.deleteTaskUserByTaskId(map);
                }
                map.put("taskRelation","3");
                //修改共享人
                if(!StringUtils.checkNull(taskManage.getShared())){
                    taskUserMapper.deleteTaskUserByTaskId(map);
                    String[] sharedArray = taskManage.getShared().split(",");
                    for(String s:sharedArray){
                        taskUser.setUserId(s);
                        taskUser.setTaskRelation("3");
                        taskUserMapper.addTaskUser(taskUser);
                    }
                }else{
                    //清空
                    taskUserMapper.deleteTaskUserByTaskId(map);
                }
                taskManageMapper.updateTaskManage(taskManage);

            }
            toJson.setMsg("success");
            toJson.setFlag(0);

        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg("erro");
            toJson.setFlag(1);
        }
        return toJson;
    }

    @Override
    public ToJson addTaskFeedback(HttpServletRequest request, TaskFeedback taskFeedback) {
        ToJson toJson = new ToJson();
        try {
            taskFeedbackMapper.addTaskFeedback(taskFeedback);
            toJson.setFlag(0);
            toJson.setMsg("success");
        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg("erro");
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson deleteTaskManage(HttpServletRequest request, int taskId) {
        ToJson toJson = new ToJson();
        try{
            taskManageMapper.deleteTaskManage(taskId);
            toJson.setMsg("success");
            toJson.setFlag(0);
        }catch (Exception e){
            toJson.setMsg("erro");
            toJson.setFlag(1);
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson queryTask(HttpServletRequest request,
                            int typeId,
                            TaskManage taskManage,
                            int myTask,int implementation,
                            String taskNameStr,
                            String manageNameStr) {
        ToJson toJson = new ToJson();
        List<TaskManage> taskManageList = new ArrayList<TaskManage>();
        Map<String,Object>map = new HashMap<String,Object>();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        try{
            List<String>participateList = new ArrayList<String>() ;
            List<String>sharedList = new ArrayList<String>() ;
            //处理多个参与、分享人
            if(!StringUtils.checkNull(taskManage.getParticipate())){
                String[] participateArray = taskManage.getParticipate().split(",");
                for(String s:participateArray){
                    participateList.add(s);
                }
            }
            if(!StringUtils.checkNull(taskManage.getShared())){
                String[] sharedArray = taskManage.getShared().split(",");
                for(String s:sharedArray){
                    sharedList.add(s);
                }
            }
            if(!StringUtils.checkNull(taskManage.getCreateDate())){
                String[] cd = taskManage.getCreateDate().split(",");
                map.put("createDate1",cd[0]);
                map.put("createDate2",cd[1]);
            }
            if(!StringUtils.checkNull(taskManage.getStartDate())){
                String[] sd = taskManage.getStartDate().split(",");
                map.put("startDate1",sd[0]);
                map.put("startDate2",sd[1]);
            }
            if(!StringUtils.checkNull(taskManage.getEndDate())){
                String[] ed = taskManage.getEndDate().split(",");
                map.put("endDate1",ed[0]);
                map.put("endDate2",ed[1]);
            }
            //高级搜索
            map.put("manageUser",taskManage.getManageUser());
            map.put("participate",participateList);
            map.put("shared",sharedList);
            map.put("taskName",taskManage.getTaskName());
            map.put("importantLevel",taskManage.getImportantLevel());
            map.put("taskStatus",taskManage.getTaskStatus());
            map.put("taskNameStr", taskNameStr);
            map.put("manageNameStr", manageNameStr);

            //判断下拉菜单我的任务
            switch (myTask) {
                case 1:
                    //我负责的与我参与的
                    map.put("myManageUser", users.getUserId());
                    map.put("manageUser",users.getUserId());
                    break;
                case 2:
                    //分享给我的
                    map.put("sharedI", users.getUserId());
                    break;
                case 3:
                    //我关注的
                    map.put("follow", users.getUserId());
                    break;
                default:
                    map.put("myManageUser", users.getUserId());
                    map.put("manageUser",users.getUserId());
                    break;
            }
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = sdf.format(date);
            switch (implementation) {
                case 1:
                    //已经延期
                    map.put("extension", dateStr);
                    break;
                case 2:
                    //即将延期
                    map.put("AboutTo", dateStr);
                    break;
                case 3:
                    //无到期日
                    map.put("maturityNo", "maturityNo");
                    break;
                default:
                    break;
            }

                /*//排序
                switch (sort){
                    case 1:
                        //重要程度排序（降序）
                        map.put("ImportanceSort","ImportanceSort");
                        break;
                    case 2:
                        //完成时间排序（降序）
                        map.put("CompleteTimeSort","CompleteTimeSort");
                        break;
                    case 3:
                        //任务起始时间（升序）
                        map.put("startTimeAsc","startTimeAsc");
                        break;
                    case 4:
                        //任务起始时间（降序）
                        map.put("startTimeDesc","startTimeDesc");
                        break;
                    case 5:
                        //任务到期时间（升序）
                        map.put("endTimeAsc","endTimeAsc");
                        break;
                    case 6:
                        //任务到期时间（降序）
                        map.put("endTimeDesc","endTimeDesc");
                        break;
                    default:
                        break;
                }*/
            map.put("typeId",typeId);
            taskManageList = taskManageMapper.queryTask(map);
            for(TaskManage taskManage1:taskManageList){
                //显示星标 是否关注
                Map mapTemp = new HashMap();
                mapTemp.put("userId",users.getUserId());
                mapTemp.put("taskRelation","2");
                mapTemp.put("taskId",taskManage1.getTaskId());
                List<TaskUser> taskUsers = taskUserMapper.queryTaskUserIdByTaskId(mapTemp);
                if(taskUsers.size()>0){
                    taskManage1.setFollow(1);
                }
                taskManage1.setManageUserName(usersMapper.getUsernameByUserId(taskManage1.getManageUser()));
                List<TaskManage>taskManages = taskManageMapper.queryChildTaskManage(taskManage1.getTaskId());
                int i = taskManages.size();
                int j =0;
                taskManage1.setTaskCount(i);//子任务总数
                for(TaskManage taskManage2:taskManages){
                    if("1".equals(taskManage2.getTaskStatus())){
                        j = j+1;
                    }
                }
                taskManage1.setCompletedCount(j);
            }
            toJson.setObj(taskManageList);
            toJson.setFlag(0);
            toJson.setMsg("success");
        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg("erro");
            e.printStackTrace();
        }
        return toJson;
    }


    @Override
    public ToJson reportTask(HttpServletResponse response,HttpServletRequest request, Integer pageSize,
                             Integer page, Boolean useFlag, int temp,String userId,String deptId,int statisObject,String startDate,String endDate) {
        ToJson toJson = new ToJson();
        try{
            //目前查询出所有用户的任务显示
            Map<String,Object> map = new HashMap<>();
            PageParams pages = new PageParams();
            pages.setPage(page);
            pages.setPageSize(pageSize);
            pages.setUseFlag(useFlag);
            map.put("page", pages);
            if(!StringUtils.checkNull(userId)){
                String[] userArray = userId.split(",");
                map.put("userId",userArray);
            }
            if(!StringUtils.checkNull(deptId)){
                String[] deptArray = deptId.split(",");
                map.put("deptId",deptArray);
            }
            // 2020、9、2  任务管理-任务报表 加入部门筛选，sql有其他地方用  故新写
            List<Users> usersList = usersMapper.getAllUserInfoPlus(map);
            List<TaskManage> taskManages =  new ArrayList<>();
            for(Users users:usersList){
                TaskManage taskManageResult = new TaskManage();
                Department department = departmentMapper.selectByDeptId(users.getDeptId());
                taskManageResult.setDeptName(department.getDeptName());
                taskManageResult.setManageUser(users.getUserName());
                //统计任务
                int taskCount =0;
                int processingCount =0;
                int postponedCount =0;
                int completedCount =0;
                Map mapTask = new HashMap();
                switch (statisObject){
                    case 1:
                        //负责人
                        mapTask.put("manageUser",users.getUserId());
                        break;
                    case 2:
                        //参与人
                        mapTask.put("participate",users.getUserId());
                        break;
                    case 3:
                        //共享人
                        mapTask.put("shared",users.getUserId());
                        break;
                    default:
                        mapTask.put("default",users.getUserId());
                        break;
                }
                if(!StringUtils.checkNull(startDate)){
                    String[] startDateArray = startDate.split("\\|");
                    mapTask.put("startDate1",startDateArray[0]);
                    mapTask.put("startDate2",startDateArray[1]);
                }
                if(!StringUtils.checkNull(endDate)){
                    String[] endDateArray = endDate.split("\\|");
                    mapTask.put("endDate1",endDateArray[0]);
                    mapTask.put("endDate2",endDateArray[1]);
                }
                List<TaskManage> taskManagesList = taskManageMapper.queryTastCount1(mapTask);
                for(TaskManage taskManage:taskManagesList){
                    taskManageResult.setManageUser(users.getUserName());
                    taskManageResult.setDeptName(department.getDeptName());
                    if("0".equals(taskManage.getTaskStatus())){
                        processingCount = processingCount+1;
                    }else{
                        completedCount = completedCount +1;
                    }
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					
                    String dateStr = sdf.format(date);
					dateStr = dateStr+" 00:00:00";
                    if(dateStr.compareTo(taskManage.getEndDate())==1){
                        postponedCount = postponedCount+1;
                    }
                }
                //任务数 SELECT DISTINCT
                taskManageResult.setTaskCount(taskManagesList.size());
                taskManageResult.setProcessingCount(processingCount);
                taskManageResult.setPostponedCount(postponedCount);
                taskManageResult.setCompletedCount(completedCount);
                //完成率 已完成/任务数
                if(completedCount==0&&taskManagesList.size()==0){
                    taskManageResult.setCompleRate(0);
                }else{
                    float compleRate=(float)completedCount/taskManagesList.size();
                    DecimalFormat fmt = new DecimalFormat("##0.00");
                    String s = fmt.format(compleRate);
                    float f1 = Float.parseFloat(s);
                    taskManageResult.setCompleRate(f1);
                }
                taskManages.add(taskManageResult);

            }
            if(temp == 1){ //导出
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateStr = sdf.format(date);
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("任务报表", 7);
                String[] secondTitles = {"人员", "部门","任务数","进行中","已延期","已完成","完成率"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"manageUser","deptName","taskCount","processingCount","postponedCount","completedCount","compleRate"};
                SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, taskManages, beanProperty);
                ServletOutputStream out = response.getOutputStream();
                String filename = "任务报表"+dateStr+".xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
            toJson.setObj(taskManages);
            toJson.setTotleNum(pages.getTotal());
            toJson.setMsg("success");
            toJson.setFlag(0);
        }catch (Exception e){
            toJson.setMsg("erro");
            toJson.setFlag(1);
            e.printStackTrace();
        }
        return toJson;
    }


    public List getSuperiorDepartment(int deptId){
        List list = new ArrayList();
        list.add(deptId);
        int deptIdSuper = departmentMapper.getParenDeptIdBydeptId(deptId);
        if(deptIdSuper!=0){
            getSuperiorDepartment(deptIdSuper);
        }
        return  list;
    }

    @Override
    public ToJson reportTaskType(HttpServletResponse response, HttpServletRequest request, Integer pageSize, Integer page, Boolean useFlag, String userId,int temp) {
        ToJson toJson = new ToJson();
        try{
            List<TaskManage> taskManagesList =taskManageMapper.queryTastCount(userId);
            List<TaskManage> list = new ArrayList<>();
            Map map = new HashMap();
            map.put("userId",userId);
            switch (temp){
               case 1 ://任务数
                   toJson.setObj(taskManagesList);
                   break;
               case 2 ://进行中
                    for(TaskManage taskManage:taskManagesList){
                        if("0".equals(taskManage.getTaskStatus())){
                            list.add(taskManage);
                        }
                    }
                   toJson.setObj(list);
                   break;
               case 3 ://已延期
                   Date date = new Date();
                   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                   String dateStr = sdf.format(date);
                   for(TaskManage taskManage:taskManagesList){
                       if(dateStr.compareTo(taskManage.getEndDate())==1){
                           list.add(taskManage);
                       }
                   }
                   toJson.setObj(list);
                   break;
               default://已完成
                   for(TaskManage taskManage:taskManagesList){
                       if("1".equals(taskManage.getTaskStatus())){
                           list.add(taskManage);
                       }
                   }
                   toJson.setObj(list);
                   break;
            }
            toJson.setMsg("success");
            toJson.setFlag(0);
        }catch (Exception e){
            toJson.setMsg("erro");
            toJson.setFlag(1);
            e.printStackTrace();
        }

        return toJson;
    }

    @Override
    public ToJson batchUrgeTask(HttpServletRequest request,String taskId, String urgeContent, String remind, String otherPeople, String reminder) {
        ToJson toJson = new ToJson();
        try{
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            if(!StringUtils.checkNull(taskId)){
                String[] taskIdArray = taskId.split(",");
                if(!StringUtils.checkNull(reminder)){
                    String[] reminderArray = reminder.split(",");
                    for(String string:reminderArray){
                        if("1".equals(string)){//内部消息
                            final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
                            String title = "您有新的工作任务需要办理";
                            for(String s:taskIdArray){
                                TaskManage taskManage = taskManageMapper.queryTaskManageByTaskId(Integer.valueOf(s));
                                urgeContent = "您有新的工作任务需要办理!任务号"+s+"，工作名称/文号："+taskManage.getTaskName();
                                String remindUrl = "/task/taskManage?taskId="+s;
                                SmsBody smsBody = new SmsBody(users.getUserId(),"31", DateFormat.getTime(DateFormat.getCurrentTime()),remindUrl,urgeContent);
                                Map mapTemp = new HashMap();
                                mapTemp.put("flag",0);
                                mapTemp.put("smsType",31);
                                if(!StringUtils.checkNull(otherPeople)){//其他人
                                    String[] otherPeopleArray = otherPeople.split(",");
                                    for(String str:otherPeopleArray){
                                        mapTemp.put("userId",str);
                                        List<SmsBodyExtend> SmsBodyList = smsBodyMapper.getWillDocSendOrReceive(mapTemp);
                                        if(SmsBodyList.size()==0){
                                            smsBody.setToId(str);
                                            smsService.saveSms(smsBody, str, "1", "1", title, urgeContent, sqlType);//存储事物提醒并推送消息
                                        }
                                    }
                                }
                                if(!StringUtils.checkNull(remind)){
                                    String[] remindArray = remind.split(",");
                                    for(String s1:remindArray){
                                        if("1".equals(s1)){//负责人
                                            TaskManage taskManage1 = taskManageMapper.queryTaskManageByTaskId(Integer.valueOf(s));
                                            mapTemp.put("userId",taskManage1.getManageUser());
                                            mapTemp.put("remindUrl",remindUrl.trim());
                                            List<SmsBodyExtend> SmsBodyList = smsBodyMapper.getWillDocSendOrReceive(mapTemp);
                                            if(SmsBodyList.size()==0){
                                                smsBody.setToId(taskManage1.getManageUser());
                                                smsService.saveSms(smsBody, taskManage1.getManageUser(), "1", "1", title, urgeContent, sqlType);//存储事物提醒并推送消息
                                            }

                                        }else{//参与人
                                            Map map = new HashMap();
                                            map.put("taskId",s);
                                            map.put("taskRelation",1);
                                            List<TaskUser> taskUserList = taskUserMapper.queryTaskUserIdByTaskId(map);
                                            for(TaskUser taskUser:taskUserList){
                                                mapTemp.put("userId",taskUser.getUserId());
                                                List<SmsBodyExtend> SmsBodyList = smsBodyMapper.getWillDocSendOrReceive(mapTemp);
                                                if(SmsBodyList.size()==0){
                                                    smsBody.setToId(taskUser.getUserId());
                                                    smsService.saveSms(smsBody, taskUser.getUserId(), "1", "1", title, urgeContent, sqlType);//存储事物提醒并推送消息
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }else{//手机短信
                            StringBuilder stringBuilderUserId = new StringBuilder();
                            final StringBuffer mobileString = new StringBuffer();
                            for(String s:taskIdArray) {
                                TaskManage taskManage = taskManageMapper.queryTaskManageByTaskId(Integer.valueOf(s));
                                if (!StringUtils.checkNull(otherPeople)) {//其他人
                                    String[] otherPeopleArray = otherPeople.split(",");
                                    for (String str : otherPeopleArray) {
                                        Users users1 = usersMapper.findUsersByuserId(str);
                                        stringBuilderUserId.append(users1.getUserId() + ",");
                                        String mobile = users1.getMobilNo();
                                        if (mobile != null && !mobile.equals("")) {
                                            mobileString.append(mobile + ",");
                                        }
                                    }
                                }
                                if(!StringUtils.checkNull(remind)) {
                                    String[] remindArray = remind.split(",");
                                    for (String s1 : remindArray) {
                                        if("1".equals(s1)){//负责人
                                            TaskManage taskManage1 = taskManageMapper.queryTaskManageByTaskId(Integer.valueOf(s));
                                            Users users1 = usersMapper.findUsersByuserId(taskManage1.getManageUser());
                                            stringBuilderUserId.append(users1.getUserId() + ",");
                                            String mobile = users1.getMobilNo();
                                            if (mobile != null && !mobile.equals("")) {
                                                mobileString.append(mobile + ",");
                                            }
                                        } else {//参与人
                                            Map map = new HashMap();
                                            map.put("taskId", s);
                                            map.put("taskRelation", 1);
                                            List<TaskUser> taskUserList = taskUserMapper.queryTaskUserIdByTaskId(map);
                                            for (TaskUser taskUser : taskUserList) {
                                                Users users1 = usersMapper.findUsersByuserId(taskUser.getUserId());
                                                stringBuilderUserId.append(users1.getUserId() + ",");
                                                String mobile = users1.getMobilNo();
                                                if (mobile != null && !mobile.equals("")) {
                                                    mobileString.append(mobile + ",");
                                                }
                                            }
                                        }

                                    }
                                }
                                StringBuffer mobile1;
                                mobile1 = !"".equals(mobileString.toString()) ? mobileString.deleteCharAt(mobileString.length() - 1) : new StringBuffer();
                                SysPara sysPara = sysParaMapper.querySysPara("MOBILE_SMS_SET");
                                if (sysPara.getParaValue().equals("0") && !"".equals(mobile1.toString())) {
                                    String stime = "";
                                    Sms2Priv sms2Priv = new Sms2Priv();
                                    sms2Priv.setStartTime(stime);
                                    Map<String, String> maps = new HashMap<String, String>();
                                    StringBuffer contextString = new StringBuffer("您有新的工作任务需要办理！");
                                    List<SmsSettings> list = smsSettingsMapper.selectSmsSettings(new HashMap<String, Object>());
                                    for (SmsSettings smsSettings : list) {
                                        smsSettings.setSign("sign=" + smsSettings.getSign());
                                        if ("湖北移动".equals(smsSettings.getName())) {
                                            String url = smsSettings.getProtocol() + "://" + smsSettings.getHost() + "/" + smsSettings.getPort();
                                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                                            String[] p = smsSettings.getPwd().split("=");
                                            String str1 = p[1] + sdf.format(new Date());
                                            String str2 = Md5Util.getMd5String(str1);
                                            maps.put("sign", str2);
                                            maps.put("timestamp", sdf.format(new Date()));
                                            String[] username1 = smsSettings.getUsername().split("=");
                                            maps.put("userName", username1[1]);
                                            maps.put("phones", mobile1.toString());
                                            maps.put("msgContent", contextString.toString());
                                            String[] extend1 = smsSettings.getExtend1().split("=");
                                            maps.put("serviceCode", extend1[1]);
                                            maps.put("mhtMsgIds", mobile1.toString());
                                            maps.put("encoding", "utf-8");
                                            maps.put("priority", "5");
                                            String msgResult = HttpSend.sendPost(url, maps);
                                            System.out.println("发送结果为：" + msgResult);
                                        } else {
                                            try {
                                                send.doPost(mobileString, contextString, smsSettings.getProtocol(), smsSettings.getHost(), smsSettings.getPort(),
                                                        smsSettings.getUsername(), smsSettings.getPwd(), smsSettings.getContentField(),
                                                        smsSettings.getCode(), smsSettings.getMobile(), smsSettings.getTimeContent(), smsSettings.getSign(), smsSettings.getLocation(),
                                                        smsSettings.getExtend1(), smsSettings.getExtend2(), smsSettings.getExtend3(), smsSettings.getExtend4(), smsSettings.getExtend5(),
                                                        sms2Priv.getStartTime());
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            toJson.setMsg("success");
            toJson.setFlag(0);
        }catch (Exception e){
            toJson.setMsg("erro");
            toJson.setFlag(1);
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson queryManageRole(HttpServletRequest request, String taskId) {
        ToJson toJson = new ToJson();
        try{
            List list = new ArrayList();
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("userId",users.getUserId());
            map.put("taskId",taskId);

            String s = taskManageMapper.queryMangeUser(taskId);
            if(users.getUserId().equals(s)){
                list.add("4");
                toJson.setObj(list);
                return toJson;
            }
            String  ss = taskUserMapper.queryTaskUserRole(map);
            list.add(ss);
            toJson.setObj(list);
            return toJson;
        }catch (Exception e){
            e.printStackTrace();
        }
        return toJson;
    }
}
